//144. 二叉树的前序遍历
//思路：1.求出二叉树的节点个书
//2.开辟动态内存
//3.前序遍历，将前序遍历的节点的val放到内存中

// C语言版本
//#include <stdlib.h>
//
//struct TreeNode {
//    int val;
//    struct TreeNode* left;
//    struct TreeNode* right;
//};
//int TreeSize(struct TreeNode* root)
//{
//    if (NULL == root)
//        return 0;
//
//    return TreeSize(root->left)
//        + TreeSize(root->right) + 1;
//}
//void _preorder(struct TreeNode* root, int* a, int* pi)
//{
//    if (NULL == root)
//        return;
//
//    a[(*pi)++] = root->val;
//    _preorder(root->left, a, pi);
//    _preorder(root->right, a, pi);
//}
//int* preorderTraversal(struct TreeNode* root, int* returnSize) {
//    *returnSize = TreeSize(root);
//    int* a = (int*)malloc(*returnSize * sizeof(int));
//    if (NULL == a)
//        return NULL;
//    int i = 0;
//
//    _preorder(root, a, &i);
//    return a;
//}


// C++ 非递归版本
#include <stack>
#include <vector>
using namespace std;

struct TreeNode 
{
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};
class Solution
{
public:
    vector<int> preorderTraversal(TreeNode* root)
    {
        stack<TreeNode*> st;
        vector<int> ret;
        TreeNode* cur = root;

        // 左路节点
        // 左路节点的右子树
        while (cur || !st.empty())
        {
            while (cur)
            {
                st.push(cur);
                ret.push_back(cur->val);

                cur = cur->left;
            }
            // 子问题方式访问左路节点的右子树
            TreeNode* top = st.top();
            st.pop();
            cur = top->right;
        }
        return ret;
    }
};